var app = getApp();
//声明全局变量
let proListToTop = [],
  menuToTop = [],
  MENU = 0,
  windowHeight, timeoutId;
// MENU ==> 是否为点击左侧进行滚动的，如果是，则不需要再次设置左侧的激活状态
import Toast from 'tdesign-miniprogram/toast/index';
import TabMenu from './data';

import {
  fetchGood
} from '../../services/good/fetchGood';
import {
  fetchActivityList
} from '../../services/activity/fetchActivityList';

import {
  Index
} from '../../request/api/common';
const API = new Index();
Page({

  data: {
    currentActiveIndex: 0,
    CustomBar: app.globalData.CustomBar,
    height: app.globalData.deviceInfo.windowHeight - app.globalData.CustomBar,
    // 接口返回的商品数组
    navList: TabMenu.list,
    storeGoods: TabMenu.cartList,
    isCartListPopupShow: false,
    activeKey: 0,
    subActiveKey: 0,
    primaryImage: '',
    specImg: '',
    commentsList: [],
    commentsStatistics: {
      badCount: 0,
      commentCount: 0,
      goodCount: 0,
      goodRate: 0,
      hasImageCount: 0,
      middleCount: 0,
    },
    isShowPromotionPop: false,
    activityList: [],
    details: {},
    goodsTabArray: [{
        name: '商品',
        value: '', // 空字符串代表置顶
      },
      {
        name: '详情',
        value: 'goods-page',
      },
    ],
    storeLogo: '',
    storeName: '云mall标准版旗舰店',
    jumpArray: [{
        title: '首页',
        url: '/pages/home/home',
        iconName: 'home',
      },
      {
        title: '购物车',
        url: '/pages/cart/index',
        iconName: 'cart',
        showCartNum: true,
      },
    ],
    isStock: true,
    cartNum: 0,
    soldout: false,
    buttonType: 1,
    buyNum: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isCartListPopupShow: false,
    isAllSelectedSku: false,
    buyType: 0,
    outOperateStatus: false, // 是否外层加入购物车
    operateType: 0,
    selectSkuSellsPrice: 0,
    maxLinePrice: 0,
    minSalePrice: 0,
    maxSalePrice: 0,
    list: [],
    spuId: '',
    navigation: {
      type: 'fraction'
    },
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    soldNum: 0, // 已售数量
    details: {},
    skuArray: [],
    isStock: true,
    showCartBar: true,
    outOperateStatus: false, // 是否外层加入购物车
  },
  onLoad: function (e) {
    API.goodsList().then(res => {
      this.setData({
        navList: res.data
      })
    })
  },
  onReady() {
    // 确保页面数据已经刷新完毕~
    setTimeout(() => {
      this.getAllRects()
    }, 20)
  },
  //购物车弹框
  showCartGroupList() {
    this.setData({
      isCartListPopupShow: true
    })
  },
  changeMenu(e) {
    // 改变左侧tab栏操作
    if (Number(e.currentTarget.id) === this.data.currentActiveIndex) return
    MENU = 1
    this.setData({
      currentActiveIndex: Number(e.currentTarget.id),
      rightProTop: proListToTop[Number(e.currentTarget.id)]
    })
    this.setMenuAnimation(Number(e.currentTarget.id))
  },
  scroll(e) {
    for (let i = 0; i < proListToTop.length; i++) {
      if (e.detail.scrollTop < proListToTop[i] && i !== 0 && e.detail.scrollTop > proListToTop[i - 1]) {
        return this.setDis(i)
      }
    }
    // 找不到匹配项，默认显示第一个数据
    if (!MENU) {
      this.setData({
        currentActiveIndex: 0
      })
    }
    MENU = 0
  },
  setDis(i) {
    // 设置左侧menu栏的选中状态
    if (i !== this.data.currentActiveIndex + 1 && !MENU) {
      this.setData({
        currentActiveIndex: i - 1
      })
    }
    MENU = 0
    this.setMenuAnimation(i)
  },
  setMenuAnimation(i) {
    // 设置动画，使menu滚动到指定位置。
    let self = this
    if (menuToTop[i].animate) {
      // 节流操作
      if (timeoutId) {
        clearTimeout(timeoutId)
      }
      timeoutId = setTimeout(() => {
        self.setData({
          leftMenuTop: (menuToTop[i].top - windowHeight)
        })
      }, 50)
    } else {
      if (this.data.leftMenuTop === 0) return
      this.setData({
        leftMenuTop: 0
      })
    }
  },
  getActiveReacts() {
    wx.createSelectorQuery().selectAll('.c-sidebar-item-active').boundingClientRect(function (rects) {
      return rects[0].top
    }).exec()
  },
  getAllRects() {
    wx.createSelectorQuery().selectAll('.pro-item').boundingClientRect(res => {})
    // 获取商品数组的位置信息
    wx.createSelectorQuery().selectAll('.pro-item').boundingClientRect(function (rects) {
      rects.forEach(function (rect) {
        // 这里减去44是根据你的滚动区域距离头部的高度，如果没有高度，可以将其删去
        proListToTop.push(rect.top)
      })
    }).exec()

    // 获取menu数组的位置信息
    wx.createSelectorQuery().selectAll('.c-sidebar-item').boundingClientRect(function (rects) {
      // console.log(rects)
      wx.getSystemInfo({
        success: function (res) {
          windowHeight = res.windowHeight / 2
          // console.log(rects)
          rects.forEach(function (rect) {
            menuToTop.push({
              top: rect.top,
              animate: rect.top > windowHeight
            })
          })
        }
      })
    }).exec()
  },
  // 获取系统的高度信息
  getSystemInfo() {
    let self = this
    wx.getSystemInfo({
      success: function (res) {
        windowHeight = res.windowHeight / 2
      }
    })
  },
  handlePopupHide() {
    this.setData({
      showCartBar: true,
      isCartListPopupShow: false,
      isSpuSelectPopupShow: false,
    });
  },
  //购物车弹框
  showCartGroupList() {
    this.setData({
      isCartListPopupShow: true
    })
  },
  selectSpecsName(selectSpecsName) {
    if (selectSpecsName) {
      this.setData({
        selectedAttrStr: selectSpecsName,
      });
    } else {
      this.setData({
        selectedAttrStr: '',
      });
    }
  },
  showSkuSelectPopup(type) {
    this.setData({
      buyType: type || 0,
      outOperateStatus: type >= 1,
      isSpuSelectPopupShow: true,
    });
  },
  chooseSpecItem(e) {
    const {
      specList
    } = this.data.details;
    const {
      selectedSku,
      isAllSelectedSku
    } = e.detail;
    if (!isAllSelectedSku) {
      this.setData({
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      isAllSelectedSku,
    });
    this.getSkuItem(specList, selectedSku);
  },

  getSkuItem(specList, selectedSku) {
    const {
      skuArray,
      primaryImage
    } = this.data;
    const selectedSkuValues = this.getSelectedSkuValues(specList, selectedSku);
    let selectedAttrStr = ` 件  `;
    selectedSkuValues.forEach((item) => {
      selectedAttrStr += `，${item.specValue}  `;
    });
    // eslint-disable-next-line array-callback-return
    const skuItem = skuArray.filter((item) => {
      let status = true;
      (item.specInfo || []).forEach((subItem) => {
        if (
          !selectedSku[subItem.specId] ||
          selectedSku[subItem.specId] !== subItem.specValueId
        ) {
          status = false;
        }
      });
      if (status) return item;
    });
    this.selectSpecsName(selectedSkuValues.length > 0 ? selectedAttrStr : '');
    if (skuItem) {
      this.setData({
        selectItem: skuItem,
        selectSkuSellsPrice: skuItem.price || 0,
      });
    } else {
      this.setData({
        selectItem: null,
        selectSkuSellsPrice: 0,
      });
    }
    this.setData({
      specImg: skuItem && skuItem.skuImage ? skuItem.skuImage : primaryImage,
    });
  },
  // 获取已选择的sku名称
  getSelectedSkuValues(skuTree, selectedSku) {
    const normalizedTree = this.normalizeSkuTree(skuTree);
    return Object.keys(selectedSku).reduce((selectedValues, skuKeyStr) => {
      const skuValues = normalizedTree[skuKeyStr];
      const skuValueId = selectedSku[skuKeyStr];
      if (skuValueId !== '') {
        const skuValue = skuValues.filter((value) => {
          return value.specValueId === skuValueId;
        })[0];
        skuValue && selectedValues.push(skuValue);
      }
      return selectedValues;
    }, []);
  },

  normalizeSkuTree(skuTree) {
    const normalizedTree = {};
    skuTree.forEach((treeItem) => {
      normalizedTree[treeItem.specId] = treeItem.specValueList;
    });
    return normalizedTree;
  },
  changeNum(e) {
    this.setData({
      buyNum: e.detail.buyNum,
    });
  },
  specsConfirm() {
    const {
      buyType
    } = this.data;
    if (buyType === 1) {
      this.gotoBuy();
    } else {
      this.addCart();
    }
    // this.handlePopupHide();
  },
  //删除购物车商品
  deleteCartGood(e) {
    var {
      goods
    } = e.detail
    console.log(goods)
  },
  //清空购物车
  clearCart() {
    this.handlePopupHide();
    this.setData({
      'storeGoods[0].promotionGoodsList[0].goodsPromotionList': []
    })
  },
  addCart() {
    const {
      isAllSelectedSku
    } = this.data;
    console.log(isAllSelectedSku)
    Toast({
      context: this,
      selector: '#t-toast',
      message: isAllSelectedSku ? '点击加入购物车' : '请选择规格',
      icon: '',
      duration: 1000,
    });
  },
  //去结算
  onToSettle() {
    const goodsRequestList = [];
    this.data.storeGoods.forEach((store) => {
      store.promotionGoodsList.forEach((promotion) => {
        promotion.goodsPromotionList.forEach((m) => {
          // if (m.isSelected == 1) {
          goodsRequestList.push(m);
          // }
        });
      });
    });
    wx.setStorageSync(
      'order.goodsRequestList',
      JSON.stringify(goodsRequestList),
    );
    wx.navigateTo({
      url: '/pages/order/order-confirm/index?type=cart'
    });
  },
  gotoBuy(type) {
    const {
      isAllSelectedSku,
      buyNum
    } = this.data;
    if (!isAllSelectedSku) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
        icon: '',
        duration: 1000,
      });
      return;
    }
    this.handlePopupHide();
    const query = {
      quantity: buyNum,
      storeId: '1',
      spuId: this.data.spuId,
      goodsName: this.data.details.title,
      skuId: type === 1 ? this.data.skuList[0].skuId : this.data.selectItem.skuId,
    };
    let urlQueryStr = obj2Params({
      goodsRequestList: JSON.stringify([query]),
    });
    urlQueryStr = urlQueryStr ? `?${urlQueryStr}` : '';
    const path = `/pages/order/order-confirm/index${urlQueryStr}`;
    wx.navigateTo({
      url: path,
    });
  },
  onParentChange(event) {
    this.setActiveKey(event.detail.index, 0).then(() => {
      this.triggerEvent('change', [
        this.data.activeKey,
        this.data.subActiveKey,
      ]);
    });
  },
  onChildChange(event) {
    this.setActiveKey(this.data.activeKey, event.detail.index).then(() => {
      this.triggerEvent('change', [
        this.data.activeKey,
        this.data.subActiveKey,
      ]);
    });
  },
  onIconTap(e) {

    var list = this.data.storeGoods[0].promotionGoodsList[0].goodsPromotionList
    var obj = e.currentTarget.dataset.goods
    // var obj = {
    //   "uid": "88888888205468",
    //   "saasId": "88888888",
    //   "storeId": "1000",
    //   "spuId": "12",
    //   "skuId": "135691622",
    //   "isSelected": 1,
    //   "thumb": "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-3a.png",
    //   "title": "腾讯极光盒子",
    //   "primaryImage": "https://cdn-we-retail.ym.tencent.com/tsr/goods/dz-3a.png",
    //   "quantity": 1,
    //   "stockStatus": true,
    //   "stockQuantity": 3,
    //   "price": "9900",
    //   "originPrice": "16900",
    //   "tagPrice": null,
    //   "titlePrefixTags": [{
    //     "text": "新品"
    //   }, {
    //     "text": "火爆"
    //   }],
    //   "roomId": null,
    //   "specInfo": [{
    //     "specTitle": "颜色",
    //     "specValue": "经典白"
    //   }, {
    //     "specTitle": "类型",
    //     "specValue": "经典套装"
    //   }],
    //   "joinCartTime": "2020-06-29T07:55:40.000+0000",
    //   "available": 1,
    //   "putOnSale": 1,
    //   "etitle": null
    // }
    obj.specInfo = []
    obj.thumb = obj.primaryImage
    obj.num = 1
    list.push(obj)
    this.setData({
      'storeGoods[0].promotionGoodsList[0].goodsPromotionList': list
    })
  },
  onSelectTap() {
    this.getDetail(3)
    this.showSkuSelectPopup(2)
    this.setData({
      // showCartBar: false
    })
    console.log('点击了选择')
  },
  goodsDetail(e) {
    console.log(e)
    const spuId = 3
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${spuId}`,
    });
  },
  getDetail(spuId) {
    Promise.all([fetchGood(spuId), fetchActivityList()]).then((res) => {

      const [details, activityList] = res;
      const skuArray = [];
      const {
        skuList,
        primaryImage,
        isPutOnSale,
        minSalePrice,
        maxSalePrice,
        maxLinePrice,
        soldNum,
      } = details;
      skuList.forEach((item) => {
        skuArray.push({
          skuId: item.skuId,
          quantity: item.stockInfo ? item.stockInfo.stockQuantity : 0,
          specInfo: item.specInfo,
        });
      });
      const promotionArray = [];
      activityList.forEach((item) => {
        promotionArray.push({
          tag: item.promotionSubCode === 'MYJ' ? '满减' : '满折',
          label: '满100元减99.9元',
        });
      });
      this.setData({
        details,
        activityList,
        isStock: details.spuStockQuantity > 0,
        maxSalePrice: maxSalePrice ? parseInt(maxSalePrice) : 0,
        maxLinePrice: maxLinePrice ? parseInt(maxLinePrice) : 0,
        minSalePrice: minSalePrice ? parseInt(minSalePrice) : 0,
        list: promotionArray,
        skuArray: skuArray,
        primaryImage,
        soldout: isPutOnSale === 0,
        soldNum,
      });
    });
  },
  changCategory(event) {
    const {
      item
    } = event.currentTarget.dataset;
    this.triggerEvent('changeCategory', {
      item,
    });
  },
  setActiveKey(key, subKey) {
    return new Promise((resolve) => {
      this.setData({
          activeKey: key,
          subActiveKey: subKey,
        },
        () => {
          resolve();
        },
      );
    });
  },

})